/*********************************************************************
 *
 *  elksip - a multi-platform Sip Phone Server
 *
 *  file: contact.h  sip Msg contact
 *
 *  Copyright 2011-2012 Elksip.
 *
 ********************************************************************/

#include "contact.h"
#include "sip_inc.h"
#include "sip_debug.h"
#include "sip.h"

void Sip_Contact_init(Sip_Contact *contact)
{
	memset(contact, 0, sizeof(Sip_Contact));
}
void Sip_Contact_free(Sip_Contact *contact)
{

    sip_free(contact->name);
    sip_free(contact->domain);
    sip_free(contact->expires);

}
void Sip_Contact_print(Sip_Contact *contact)
{

}

void Sip_Contact2str(const Sip_Contact *Contact, Sip_string *str)
{
    char buf[128] = {0};
    snprintf(buf, sizeof(buf), "Contact: <sip:%s@%s>;expires=%s",
		Contact->name, Contact->domain, Contact->expires);
    sip_str_append(str, buf);
    sip_str_append_CRLF(str);
}

int  Sip_Contact_Parse(Sip_Message* msg, const char *value)
{
    msg->contact =(Sip_Contact*) malloc(sizeof(Sip_Contact));
	Sip_Contact_init(msg->contact);
    Sip_Contact *contact = (msg->contact);
    const char *colon_index = strchr(value, ':');
    if(colon_index==NULL)
        return -1;
    const char *art_index = strchr(colon_index, '@');
    if(art_index==NULL)
        return -1;
    int len = art_index-colon_index;
    char buf[64] = {0};
    strncpy(buf, colon_index+1, len-1);
    contact->name = strdup(buf);

    const char *great_index = strchr(art_index, '>');
    len = great_index -art_index;
    contact->domain = (char*)malloc(len);
    memset(contact->domain, 0, len);
    strncpy(contact->domain, art_index+1, len-1);

    SIP_DEBUG_INFO("zhang  :[%s]\n", contact->domain);
    const char *equal_index = strchr(great_index, '=');
    if(equal_index!=NULL)
    {
        len = strlen(equal_index);
		contact->expires = (char*)malloc(len-1);
        strncpy(contact->expires, equal_index+1, len-2);
    }
    return 0;
        

}